<?php
//decode by http://奥森世纪/
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/1/19
 * Time: 19:56
 */

namespace app\home\controller;

use think\console\Command;
use think\console\Input;
use think\console\Output;

use app\admin\model\Config;
use app\home\model\CreditRecord;
use app\home\model\Member;
use app\admin\model\InvitationRebateRecord;
use think\Db;
use think\Log;

class Wechat extends  Base{
    /*
   * 雇主发布任务后1小时内不审核任务，系统会自动审核通过，佣金进入用户帐号中
   */
    public function ordercheckout()
    {
        $setting = ['check_order_limit_time' => 0, 'invitation_rebate' => 0];
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['check_order_limit_time'])){
                $setting['check_order_limit_time'] = intval($setting['check_order_limit_time']);
            }
            if(!empty($setting['invitation_rebate'])){
                $setting['invitation_rebate'] = round(floatval($setting['invitation_rebate']/100),2);
            }
        }
        try {
            $task_joins = \db('task_join')
                ->alias('m')
                ->join('tb_task n',"n.id = m.task_id and m.update_time <= (".time()."-n.task_checkout_time*60*60)")
                ->field('m.*')
                ->where(['m.delflag' => 1, 'm.status' => 2])
                ->limit(500)
                ->select();
            $ids = [];

          


            foreach ($task_joins as $joinInfo) {
                $id = $joinInfo['id'];
                $ids[] = $joinInfo['id'];

                $params = \app\home\model\Task::getInfoById($joinInfo['task_id']);
                if(empty($params)){
                   
                    \app\home\model\TaskJoin::updateInfoById($id, ['delflag' => 2]);

                    $error =  $joinInfo['task_id'] . "---任务不存在\n";
                    //$output->writeln($error);
                    Log::error(__FILE__.':'.__LINE__.' ' . $error);
                    continue;
                }

                $joinMemberInfo = Member::getUserInfoById($joinInfo['uid']);
                if (!$joinMemberInfo){
                   
                    \app\home\model\TaskJoin::updateInfoById($id, ['delflag' => 2]);

                    $error =  $joinInfo['uid'] . "---任务会员不存在\n";
                    //$output->writeln($error);
                    Log::error(__FILE__.':'.__LINE__.' ' . $error);
                    continue;
                }

                $insert_task_id = $joinInfo['task_id'];

                Db::startTrans();

                $update = array(
                    'status' => 3,
                    'audit_time' => TIMESTAMP,
                    'update_time' => TIMESTAMP
                );
                $status = \app\home\model\TaskJoin::updateInfoById($id, $update);
                if(!$status){
                   
                    Db::rollback();
                    $error = $id . "---审核失败:-1\n";
                    //$output->writeln($error);
                    Log::error(__FILE__.':'.__LINE__.' ' . $error);
                    continue;
                }

                if($params['give_credit1']>0 || $params['unit_price']>0){
                   
                    $give_credit1 = $params['give_credit1'];
                    $unit_price = $params['unit_price'];
                    //VIP赠送积分
                    if($joinMemberInfo['level'] != 1){
                      //  $give_credit1 = $params['give_credit1']*$setting['zengjifen'];
                    }
                       
	                //给上级和上上级发奖励
					task_reward($joinMemberInfo,$params);

                    /* $taskService = \think\Loader::model("Task", 'common\service');
                     $taskService->invitationFirstTaskAward($joinMemberInfo, $params);*/

                    $status1 = Member::updateCreditById($joinInfo['uid'], 0, $unit_price);
                    
                    //首次完成任务给师傅和师爷奖励
                    if($joinMemberInfo['over_task_num'] ==0 ){
				         	//首次完成任务给上级奖励
				         	$credit2_dady = $setting['invitation_first_task_award'];
				         	if($joinMemberInfo['parent_uid'] && $credit2_dady>0){
						         	
						            $status1 = Member::updateCreditById($joinMemberInfo['parent_uid'], 0, $credit2_dady);
						            $status2 = CreditRecord::addInfo([
						                'uid' => $joinMemberInfo['parent_uid'],
						                'type' => 'credit2',
						                'num' => $credit2_dady,
						                'title' => '徒弟'.$joinMemberInfo['uid'].'首次完成任务奖励',
						                'remark' =>'徒弟'.$joinMemberInfo['uid'].'首次完成任务,奖励1元.',
						                'create_time' => TIMESTAMP
						            ]);
						            //添加纪录
			                		InvitationRebateRecord::addInfo([
			                            'uid' => $joinMemberInfo['parent_uid'],
			                            'num' => $credit2_dady,
			                            'task_id' => 0,
			                            'tuijian_id' =>$joinMemberInfo['uid'],
			                            'remark' => '徒弟'.$joinMemberInfo['uid'].'首次完成任务,奖励1元.',
			                            'create_time' => TIMESTAMP
			                        ]);
						            
						            //给上上级的奖励
						            $grandpa=db('member')->find($joinMemberInfo['parent_uid']);
						            $credit2_grand = $setting['shiye'];
						            if($grandpa && $grandpa['parent_uid'] && $credit2_grand>0){
							         	
							            $status1 = Member::updateCreditById($grandpa['parent_uid'], 0, $credit2_grand);
							 
							            $status2 = CreditRecord::addInfo([
							                'uid' => $grandpa['parent_uid'],
							                'type' => 'credit2',
							                'num' => $credit2_grand,
							                'title' => '徒孙'.$joinMemberInfo['uid'].'首次完成任务奖励',
							                'remark' =>'徒孙'.$joinMemberInfo['uid'].'首次完成任务,奖励0.5元.',
							                'create_time' => TIMESTAMP
							            ]);
						            
							            //添加纪录
				                		InvitationRebateRecord::addInfo([
				                            'uid' => $grandpa['parent_uid'],
				                            'num' => $credit2_grand,
				                            'task_id' => 0,
				                            'tuijian_id' =>$mems['uid'],
				                            'remark' => '徒孙'.$mems['uid'].'首次完成任务,奖励0.5元.',
				                            'create_time' => TIMESTAMP
				                        ]);
							            
						            }
				         	}
	  		}
                    
                    if(!$status1){
                        Db::rollback();
                        $error = $id . "---审核失败:-8\n";
                        //$output->writeln($error);
                        Log::error(__FILE__.':'.__LINE__.' ' . $error);
                        continue;
                    }

                    
		//发红包
		$redpackage=\db('redpackage')->where(['task_id'=>$params['id']])->find();
	
		
		if($redpackage && !$redpackage['is_over']){
				$has_send_money=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['neq',0]])->sum('money');
				$has_send_number=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['neq',0]])->count();
	
				if($has_send_money <$redpackage['money']){
					
					//要发的红包
					$send_info=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['eq',0]])->order('redpackage_record_id asc')->find();
					
					$left_money=$redpackage['money']-$has_send_money;
					
					if($send_info && $left_money>0){
						
							
							//是否最后一个用户
							if( ($has_send_number+1) == $redpackage['number'] ){
								\db('redpackage')->where(['task_id'=>$params['id']])->setField('is_over',1);
							}
							
							$get_money=$send_info['money'];
							
						     $credit2 = $joinMemberInfo['credit2']+$get_money;
					    
					       // $res1 = \db('member')->where(['uid'=>$joinInfo['uid']])->data(['credit2'=>$credit2])->update();
					          
					          $res1 = Member::updateCreditById($joinInfo['uid'], 0, $get_money);
					          
					            if(!$res1){
						            Db::rollback();
						   
			                        $error = $id . "---审核失败:-9\n";
			                        //$output->writeln($error);
			                        Log::error(__FILE__.':'.__LINE__.' ' . $error);
			                        continue;
						        }
		
		
					        $creditdata = array(
					            'uid'=>$joinInfo['uid'],
					            'type'=>'credit2',
					            'num'=>'+'.$get_money,
					            'title'=>'完成任务获得红包',
					            'remark'=>'完成任务'.$params['id'].'获得红包'.$get_money,
					            'create_time'=>time(),
					            'balance'=>$credit2,    //追加后的余额
					        );
					        $res3 = \db('credit_record')->data($creditdata)->insert();
					        if(!$res3){
					            Db::rollback();
		                        $error = $id . "---审核失败:-10\n";
		                        //$output->writeln($error);
		                        Log::error(__FILE__.':'.__LINE__.' ' . $error);
		                        continue;
					        }
					        
					        $send_info['uid']=$joinInfo['uid'];
					        $send_info['add_time']=time();
					        
					       $res4 = \db('redpackage_record')->data($send_info)->update();
					        if(!$res4){
								 Db::rollback();
		                        $error = $id . "---审核失败:-11\n";
		                        //$output->writeln($error);
		                        Log::error(__FILE__.':'.__LINE__.' ' . $error);
		                        continue;
					        }
					}
				        
				        
				        
				}
		}                   
                    
                    
               
                }

                Db::commit();
               //记录每日
                $member_info = db('member')->where('uid',$joinInfo['uid'])->find();
		        if($member_info['partition_status']==1){
		            $jackpot = db('jackpot')->where('uid',$joinInfo['uid'])->where('today_time',date('Ymd'))->find();
		            if($jackpot['num']>$member_info['partition_num']){
		                
		                $my_task_num['partition_num'] = $member_info['partition_num']+1;
		            }
		            if($jackpot['num']==$member_info['partition_num']+1){
		                	$my_task_num['partition_status']=2;
		                }
		        }
		     	 $my_task_num['over_task_num'] = $member_info['over_task_num']+1;
		        db('member')->where('uid',$joinInfo['uid'])->update($my_task_num);
        
            }
        

            Log::info(__FILE__.':'.__LINE__.' 审核前后订单');
            //$output->writeln('审核前后订单');

        } catch (Exception $e) {
            Log::error(__FILE__.':'.__LINE__.' 错误：'.$e->getMessage());
            //$output->writeln(__FILE__.':'.__LINE__.' 错误：'.$e->getMessage());
        }
    }
  

    /*
 * 用户抢单后5分钟内未上传验证，抢单将自己删除
 */

    public function delqiangdan()
    {
        //配置接单限时由后台变为前台任务显示时间
        try {
            $task_joins = \db('task_join')
                ->alias('m')
                ->join('tb_task n',"n.id = m.task_id and m.create_time <= (".time()."-n.task_time*60*60)")
                ->field('m.*')
                ->where(['m.delflag' => 1, 'm.status' => 1])
                ->limit(500)
                ->select();
            $ids = [];
            $task_ids = [];
            foreach ($task_joins as $value) {
                $ids[] = $value['id'];
                $task_ids[] = $value['task_id'];
            }

            if (!empty($ids) && !empty($task_ids)) {
                Db::startTrans();

                $status1 = \app\api\model\TaskJoin::delReceiveOrderOutTime($ids);
                if(!$status1){
                    Db::rollback();
                    Log::error(__FILE__.':'.__LINE__.' 错误：delReceiveOrderOutTime执行失败');
                    //$output->writeln('delReceiveOrderOutTime执行失败');
                }

                $status2 = \app\api\model\Task::updateTaskReceiveOrderOutTime($task_ids);
                if(!$status2){
                    Db::rollback();
                    Log::error(__FILE__.':'.__LINE__.' 错误：updateTaskReceiveOrderOutTime执行失败');
                    //$output->writeln('updateTaskReceiveOrderOutTime执行失败');
                }

                Db::commit();
            }

            Log::info(__FILE__.':'.__LINE__.' 每分钟执行接单限时超时处理');
            //$output->writeln('每分钟执行接单限时超时处理');

        } catch (Exception $e) {
            Log::error(__FILE__.':'.__LINE__.' 错误：'.$e->getMessage());
            //$output->writeln(__FILE__.':'.__LINE__.' 错误：'.$e->getMessage());
        }
    }
//	截至时间任务过期
    public function jiezhistop()
    {
        $list = \db('task')->where(['end_time'=>['elt',time()],'is_stop'=>0])->field('id')->select();
        if(!empty($list)){
            foreach ($list as $k=>$v){
                \db('task')->where(['id'=>$v['id']])->data(['is_stop'=>1])->update();
               
            }
        }
    }
    //任务不通过24小时可以重新上传，超过则自动放弃
    public function butongguo(){
        $time = time()-24*60*60;
        $list = \db('task_join')->where(['status'=>4,'is_shensu'=>0,'delflag'=>1,'audit_time'=>['lt',$time]])->select();
        if(!empty($list)){
            foreach($list as $k=>$v){
            	
                \db('task_join')->where(['id'=>$v['id']])->data(['delflag'=>2])->update();
                
            }
        }
        //给返还名额的再加一个状态标识已返还，防止重复返还成负数。。。
        $result = \db('task_join')->where(['status'=>4,'is_shensu'=>0,'delflag'=>2,'is_fanhuan'=>0])->select();
        if(!empty($result)){
            foreach($result as $k=>$v){
            	\db('task_join')->where(['id'=>$v['id']])->setField('is_fanhuan',1);
            	\db('task')->where('id',$v['task_id'])->setDec('join_num');
               
            }
        }
    }
    public function save_tasks(){
    	$result = db('task')->where('join_num','<',0)->select();
    	foreach ($result as $v){
    		$count = db('task_join')->where('task_id',$v['id'])->where('status',3)->count();
    		db('task')->where('id',$v['id'])->setField('join_num',$count);
    	}
    }

    //任务置顶到期
    public function zhidingout(){
        $list = \db('task')->select();
        if(!empty($list)){
            foreach($list as $k=>$v){
                if(time()>$v['top_end_time']){
                    \db('task')->where(['id'=>$v['id']])->data(['top_hour'=>0,'top_time'=>0,'top_fee'=>0,'top_end_time'=>0])->update();
                    
                }
            }
        }
    }

    //会员有限期截至和每天执行VIP赠送置顶时间
    public function vipend(){
    	//每天给用户当天买的宠物清零，第二天再累计
    	db('member')->where('now_day_pet','>',0)->setField('now_day_pet',0);
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
        }
        $list = \db('member')->where(['level'=>['neq',1]])->select();
        if(!empty($list)){
            foreach($list as $k=>$v){
                if((time() - $v['level_time']) > $setting['viptime']*24*60*60 ){
                    \db('member')->where(['uid'=>$v['uid']])->data(['level'=>1,'level_time'=>0])->update();
                   
                }
            }
        }


        $vip =  \db('member')->where(['level'=>['neq',1]])->select();
        if(!empty($vip)){
            foreach($vip as $m=>$n){
                \db('member')->where(['uid'=>$n['uid']])->data(['toptime'=>$setting['zengtop']])->update();
                
            }
        }
    }
    

}